﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using Usido.CRM.Core.Extensions;
using Usido.CRM.IRepository;
using Usido.CRM.Models;
using Usido.CRM.Repository;

namespace Usido.CRM.App.Forms
{
    public partial class 药品销售管理 : Form
    {
        private readonly IStockProductBalanceRepository productRepository = new StockProductBalanceRepository();
        private readonly ISupplyInfoRepository supplyInfoRepository = new SupplyInfoRepository();
        private readonly ISupplyOrderRepository supplyOrderRepository = new SupplyOrderRepository();
        private readonly ISysSupplierRepository supplierRepository = new SysSupplierRepository();

        public 药品销售管理()
        {
            InitializeComponent();
        }

        public 药品销售管理(string userId, string userName)
        {
            InitializeComponent();
            this.userId = userId;
            this.userName = userName;
            Lab_ZDR.Text = this.userName;
            Lab_ZDSS.Text = DateTime.Now.ToString("yyyy年MM月dd日  hh:mm:ss");
        }

        

        private void 采购入库管理_Load(object sender, EventArgs e)
        {
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            //加载采购订单信息
            var list = supplyOrderRepository.GetSupplyList(); 
            dgvSupplyList.AutoGenerateColumns = false;
            dgvSupplyList.DataSource = list;
            tableLayoutPanel2.Enabled = false;
          
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                int index = dataGridView1.CurrentCell.RowIndex;
            }
            catch (Exception)
            {
                MessageBox.Show("您还未选中有效行！");
            }

            DialogResult RSS = MessageBox.Show(this, "确定要删除选中行数据码？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (RSS == DialogResult.Yes)
            {
                try
                {
                    dataGridView1.Rows.RemoveAt(index);
                    MessageBox.Show("成功删除选中行数据！");
                }
                catch (Exception)
                {
                    MessageBox.Show("您还未选中有效行！");
                }
            }
        }

        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripEdit_Click(object sender, EventArgs e)
        {
            tabControl1.SelectedIndex = 1;
        }

        /// <summary>
        /// 保存/入库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripDelete_Click(object sender, EventArgs e)
        {
            if (toolStripBC_RK.Text == "保存")
            {
                SupplyOrder order = new SupplyOrder()
                {
                    CreateTime = DateTime.Now,
                    CreateUserId = this.userId.ToInt(),
                    Remark = "",
                    State = 0,
                    //SupplierId = supplyId.ToInt()
                };

                List<SupplyInfo> infoList = new List<SupplyInfo>();
 
                for (int i = 0; i < Count; i++)
                {
                    var productId = dataGridView1.Rows[i].Cells["药品编码"].Value.ToString();
                    if (productId.IsNullOrEmpty())
                    {
                        continue;
                    }
                    //var batchNumber = dataGridView1.Rows[i].Cells["批号"].Value.ToString();
                    //if (batchNumber.IsNullOrEmpty())
                    //{
                    //    MessageBox.Show($"第{i + 1}行批号不能为空");
                    //    return;
                    //}
                    var price = dataGridView1.Rows[i].Cells["单价"].Value.ToString();
                    decimal priceNew = 0;
                    if (!decimal.TryParse(price, out priceNew))
                    {
                        MessageBox.Show($"第{i + 1}行单价格式不正确");
                        return;
                    }
                    if (priceNew < 0)
                    {
                        MessageBox.Show($"第{i + 1}行单价格式不正确");
                        return;
                    }
                    var quantity = dataGridView1.Rows[i].Cells["数量"].Value.ToString();
                    decimal quantityNew = 0;
                    if (!decimal.TryParse(quantity, out quantityNew))
                    {
                        MessageBox.Show($"第{i + 1}行数量格式不正确");
                        return;
                    }
                    if (quantityNew <= 0)
                    {
                        MessageBox.Show($"第{i + 1}行数量必须大于0");
                        return;
                    }
                    var dateExpiry = dataGridView1.Rows[i].Cells["有效期至"].Value.ToString();
                    DateTime dateExpiryNew;
                    if (!DateTime.TryParse(dateExpiry, out dateExpiryNew))
                    {
                        MessageBox.Show($"第{i + 1}行有效期至格式不正确");
                        return;
                    }
                    var info = new SupplyInfo()
                    {
                        //BatchNumber = batchNumber,
                        DateExpiry = dateExpiryNew,
                        Price = priceNew,
                        ProductId = productId.ToInt(),
                        Quantity = quantityNew
                    };

                    if (infoList.Any(m => m.ProductId == info.ProductId && m.BatchNumber == info.BatchNumber && m.DateExpiry == info.DateExpiry))
                    {
                        MessageBox.Show($"第{i + 1}行数据重复，请检查");
                        return;
                    }
                    infoList.Add(info);
                }

                if (supplyOrderRepository.AddSupply(order, infoList)>0)
                {
                    MessageBox.Show("保存成功");
                    toolStripBC_RK.Text = "入库";
                    toolStripEdit.Enabled = true;
                }
                else
                {
                    MessageBox.Show("保存失败，请稍后重试");
                }
            }
            else
            {
                MessageBox.Show("入库成功！此订单已无法修改");
                toolStripBC_RK.Enabled = false;
                toolStripEdit.Enabled = false;
                toolStripAdd.Enabled = true;
            }
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripAdd_Click(object sender, EventArgs e)
        {
            tabControl1.SelectedIndex = 1;
            if (dataGridView1.Rows.Count > 0)
            {
                dataGridView1.Rows.Clear();
            }
            toolStripBC_RK.Text = "保存";
            toolStripAdd.Enabled = false;
            toolStripBC_RK.Enabled = true;
            tableLayoutPanel2.Enabled = true;
        }

        private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            //检测是被表示的控件还是DataGridViewTextBoxEditingControl
            if (e.Control is DataGridViewTextBoxEditingControl)
            {
                DataGridView dgv = (DataGridView)sender;
                //取得被表示的控件
                DataGridViewTextBoxEditingControl tb = (DataGridViewTextBoxEditingControl)e.Control;
                //事件处理器删除
                tb.TextChanged -= Tb_TextChanged1;
                tb.TextChanged -= Tb_TextChanged;
                tb.TextChanged -= Tb_TextChanged2;
                //检测对应列
                if (dgv.CurrentCell.OwningColumn.Name == "药品编码")
                {
                    // KeyPress事件处理器追加
                    tb.TextChanged += Tb_TextChanged;
                }
                if (dgv.CurrentCell.OwningColumn.Name == "数量")
                {
                    // KeyPress事件处理器追加
                    tb.TextChanged += Tb_TextChanged1; ;
                }
                if (dgv.CurrentCell.OwningColumn.Name == "单价")
                {
                    // KeyPress事件处理器追加
                    tb.TextChanged += Tb_TextChanged2; ; ;
                }
                if (dgv.CurrentCell.OwningColumn.Name == "有效期至")
                {
                    tb.Click += Tb_Click;
                }
            }
        }

        private void Tb_Click(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentCell.OwningColumn.Name == "有效期至")
            {
                panel1.Visible = true;
            }
        }

        private void Tb_TextChanged2(object sender, EventArgs e)
        {
            try
            {
                if (dataGridView1.CurrentCell.OwningColumn.Name == "有效期至")
                {
                    return;
                }
                TextBox TB = (TextBox)sender;
                double 单价;
                if (TB.Text.Trim() == "")
                {
                    单价 = 0;
                }
                else
                {
                    单价 = double.Parse(TB.Text.Trim());
                }
                double 数量 = double.Parse(dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells["数量"].Value.ToString());
                dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells["金额"].Value = "￥" + (单价 * 数量).ToString();
            }
            catch (Exception ex)
            {
            }
        }

        //计算总金额
        private void Tb_TextChanged1(object sender, EventArgs e)
        {
            try
            {
                TextBox TB = (TextBox)sender;
                double 数量;
                if (TB.Text.Trim() == "")
                {
                    数量 = 0;
                }
                else
                {
                    数量 = double.Parse(TB.Text.Trim());
                }
                double 单价 = double.Parse(dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells["零售价"].Value.ToString());
                double 会员价 = double.Parse(dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells["会员价"].Value.ToString());
                dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells["金额"].Value = "￥" + (单价 * 数量).ToString();
                dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells["会员金额"].Value = "￥" + (会员价 * 数量).ToString();
            }
            catch (Exception ex)
            {
            }
        }

        //检索药品
        private int index = -1;

        private void Tb_TextChanged(object sender, EventArgs e)
        {
            TextBox TB = (TextBox)sender;
            if (TB.Text.Trim() == "")
            {
                panel1.Visible = false;
            }
            else
            {
                index = dataGridView1.CurrentCell.RowIndex;
                string code = TB.Text.Trim();
                var productList = productRepository.GetStockInfoList(code);
                if (productList.ToList().Count > 0)
                {
                    dataGridView2.AutoGenerateColumns = false;
                    dataGridView2.DataSource = productList;
                    dataGridView2.ClearSelection();
                 
                    panel1.Visible = true;
                }
                else
                {
                    panel1.Visible = false;
                }
            }
        }

        /// <summary>
        /// 查询结果双击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView2_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                string Id = dataGridView2.SelectedRows[0].Cells["dgv2编号"].Value.ToString();
                string name = dataGridView2.SelectedRows[0].Cells["dgv2药品名称"].Value.ToString();
                string gg = dataGridView2.SelectedRows[0].Cells["dgv2规格"].Value.ToString();
                string scqy = dataGridView2.SelectedRows[0].Cells["dgv2生产企业"].Value.ToString();
                string kc = dataGridView2.SelectedRows[0].Cells["dgv2库存"].Value.ToString();
                if (decimal.Parse(kc)<=0)
                {
                    MessageBox.Show("该药品库存不足！无法出售");
                    return;
                }
                string dw = dataGridView2.SelectedRows[0].Cells["dgv2单位"].Value.ToString();
                string lsj = dataGridView2.SelectedRows[0].Cells["dgv2零售价"].Value.ToString();
                string hyjzk = dataGridView2.SelectedRows[0].Cells["dgv2会员折扣"].Value.ToString();
                //int row = dataGridView1.CurrentRow.Index;
                dataGridView1.Rows[index].Cells["药品编码"].Value = Id;
                dataGridView1.Rows[index].Cells["药品名称"].Value = name;
                dataGridView1.Rows[index].Cells["规格"].Value = gg;
                dataGridView1.Rows[index].Cells["生产企业"].Value = scqy;
                dataGridView1.Rows[index].Cells["库存"].Value = kc;
                dataGridView1.Rows[index].Cells["单位"].Value = dw;
                dataGridView1.Rows[index].Cells["零售价"].Value =lsj;
                dataGridView1.Rows[index].Cells["会员价"].Value = String.Format("{0:F}", Convert.ToDouble(lsj) * Convert.ToDouble(hyjzk) / 100);
         
                this.panel1.Visible = false;
                dataGridView1.Rows[index].Cells["药品编码"].ReadOnly = true;
                dataGridView1.Focus();
            }
            catch (Exception E)
            {
            }
        }

        private bool IsoK = true;

        //新增一行
        private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                IsoK = true;
                int Count = dataGridView1.Rows.Count;
                if (Count > 0)
                {
                    if (dataGridView1.Rows[Count - 1].Cells["药品编码"].ReadOnly)
                    {
                        for (int i = 0; i < dataGridView1.Rows[Count - 1].Cells.Count; i++)
                        {
                            if (dataGridView1.Rows[Count - 1].Cells[i].Value == null)
                            {
                                IsoK = false;
                            }
                            else
                            {
                                if (dataGridView1.Rows[Count - 1].Cells[i].Value.ToString() == "")
                                {
                                    IsoK = false;
                                }
                            }
                        }
                        if (IsoK)
                        {
                            dataGridView1.Rows.Add();
                        }
                    }
                    else
                    {
                        dataGridView2.Focus();
                    }
                }
                else
                {
                    dataGridView1.Rows.Add();
                }
            }
        }

       

        //药品检索结果
        private void dataGridView2_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Enter)
                {
                    string Id = dataGridView2.SelectedRows[0].Cells["dgv2编号"].Value.ToString();
                    string name = dataGridView2.SelectedRows[0].Cells["dgv2品名"].Value.ToString();
                    string gg = dataGridView2.SelectedRows[0].Cells["dgv2规格"].Value.ToString();
                    string scqy = dataGridView2.SelectedRows[0].Cells["dgv2生产企业"].Value.ToString();
                    string dw = dataGridView2.SelectedRows[0].Cells["dgv2单位"].Value.ToString();
                    //int row = dataGridView1.CurrentRow.Index;
                    dataGridView1.Rows[index].Cells["药品编码"].Value = Id;
                    dataGridView1.Rows[index].Cells["品名"].Value = name;
                    dataGridView1.Rows[index].Cells["规格"].Value = gg;
                    dataGridView1.Rows[index].Cells["生产企业"].Value = scqy;
                    dataGridView1.Rows[index].Cells["单位"].Value = dw;
                    this.panel1.Visible = false;
                    dataGridView1.Rows[index].Cells["药品编码"].ReadOnly = true;
                    dataGridView1.Focus();
                }
            }
            catch (Exception E)
            {
            }
        }

        private double Money = 0.00;
        private int Count = 0;
        private string userId;
        private string userName;

        private void dataGridView1_RowPostPaint_1(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Money = 0.00;
            Count = 0;
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
          e.RowBounds.Location.Y,
          dataGridView1.RowHeadersWidth - 4,
          e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics,
                  (e.RowIndex + 1).ToString(),
                   dataGridView1.RowHeadersDefaultCellStyle.Font,
                   rectangle,
                   dataGridView1.RowHeadersDefaultCellStyle.ForeColor,
                   TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
            try
            {
                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    if (dataGridView1.Rows[i].Cells["金额"].Value != null)
                    {
                        Count++;
                        double num = double.Parse(dataGridView1.Rows[i].Cells["金额"].Value.ToString().Replace("￥", ""));
                        Money += num;
                    }
                }
                Lab_HJcount.Text = "合计：" + Count.ToString() + "笔 ";
                toolStripStatusLabel2.Text = "总金额:￥" + Money.ToString();
            }
            catch (Exception ex)
            {
            }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            //string code = textBox1.Text;
            //string sql = $" WHERE (CompanyName LIKE '%{code}%' OR CompanyCode LIKE '%{code}%') AND State = 1";
            //var supplyLit = supplierRepository.GetList(sql, new { });
            //cboxSupply.DataSource = supplyLit;
            //if (supplyLit.ToList().Count > 0)
            //{
            //    cboxSupply.DroppedDown = true;
            //}
            //cboxSupply.ValueMember = nameof(SysSupplier.Id);
            //cboxSupply.DisplayMember = nameof(SysSupplier.CompanyName);
        }

        private void dataGridView1_Click(object sender, EventArgs e)
        {
            panel1.Visible = false;
        }

        private void dgvSupplyList_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                string Id = dgvSupplyList.SelectedRows[0].Cells["Id"].Value.ToString();
                this.tabControl1.SelectedIndex = 1;
            }
            catch (Exception ex)
            {
                MessageBox.Show("请选择采购订单!");
            }
        } 
        private void toolStripDropDownButton1_Click(object sender, EventArgs e)
        {
            if (dataGridView1.Rows.Count>0)
            {
                bll.PrintDataGridView.Print(dataGridView1,"药品销售制单","制单人：张三");
            }
        }
 
    
   

        private void txtHY_TextChanged(object sender, EventArgs e)
        {

        }
    }
}